<template>
  <!-- 只有在总页数大于1的时候才显示 -->
  <div class="pager-container" v-if="pageNumber">
    <!-- 首页 -->
    <a @click="handleClick(1)" :class="{ disabled: current === 1 }">|&lt;&lt;</a>
    <!-- 上一页 -->
    <a @click="handleClick(current - 1)" :class="{ disabled: current === 1 }">&lt;&lt;</a>

    <!-- 页码 -->
    <a @click="handleClick(n)" v-for="(n, i) in numbers" :key="i" :class="{ active: n === current }">{{ n }}</a>

    <!-- 下一页 -->
    <a @click="handleClick(current + 1)" :class="{ disabled: current === pageNumber }">&gt;&gt;</a>
    <!-- 尾页 -->
    <a @click="handleClick(pageNumber)" :class="{ disabled: current === pageNumber }">&gt;&gt;|</a>
  </div>
</template>

<script>
export default {
  props: {
    current: {  // 当前页码
      type: Number,
      default: 1,
    },
    total: { // 总数据数量
      type: Number,
      default: 0,
    },
    limit: { // 页容量
      type: Number,
      default: 10,
    },
    visibleNumber: { // 可以看到的数字页码最多有多少个
      type: Number,
      default: 10,
    }
  },
  computed: {
    // 总页数
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    // 得到显示的最小数字
    visibleMin() {
      let min = Math.floor(this.current - this.visibleNumber / 2);
      min < 1 && (min = 1);
      return min;
    },
    // 显示的最大数字
    visibleMax() {
      let max = this.visibleMin + this.visibleNumber - 1;
      max > this.pageNumber && (max = this.pageNumber);
      return max;
    },
    // 最终显示的页码数组
    numbers() {
      let nums = [];
      for (let i = this.visibleMin; i <= this.visibleMax; i++) {
        nums.push(i);
      }
      return nums;
    }
  },
  methods: {
    handleClick(newPage) {
      this.$emit('pageChange', newPage);
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/styles/var.less';

.pager-container {
  display: flex;
  justify-content: center;
  margin: 20px 0px;

  a {
    color: @primary;
    margin: 0 6px;
    cursor: pointer;
    user-select: none;

    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }

    &.active {
      color: @dark;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>